package com.config.ser.util;

import org.springframework.util.StringUtils;
import org.yaml.snakeyaml.Yaml;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * yaml转Map，避免Map套着Map
 */
public class YamlUtils {

    private Map<String,Object> resultMap;

    private String tempKey="";

    public YamlUtils(){
        resultMap=new LinkedHashMap<>();
    }

    private void SwitchYmalMapToMap(Object map){
        if (!(map instanceof Map)) {
            String substring = tempKey.substring(0, tempKey.length() - 1);
            resultMap.put(substring,map);
            return;
        }

        for (String key:((Map<String, Object>) map).keySet()){
            tempKey += key+".";
            SwitchYmalMapToMap(((Map<String, Object>) map).get(key));
            tempKey=tempKey.substring(0,tempKey.length()-(key.length()+1));
        }
    }

    public Map<String,Object> getYamlMap(String resources) throws IOException {
        Yaml yaml = new Yaml();
        InputStream resourceAsStream = new FileInputStream(resources);
        if (StringUtils.isEmpty(resources)){
            return null;
        }
        if (resourceAsStream==null){
            return null;
        }
        Map load = yaml.load(resourceAsStream);
        if (load==null||load.isEmpty()){
            resourceAsStream.close();
            return null;
        }
        SwitchYmalMapToMap(load);
        resourceAsStream.close();
        return this.resultMap;
    }

}